<template>
	<view class="box">
		<view class="upage__item">
			<view class="" @click="backFn">
				<u-icon name="arrow-left" color="#424242" size="24"></u-icon>
			</view>
			<view class="" style="font-size: 40rpx;color: #10181c;">
				配置雨量计
			</view>
			<view class="" style="width: 240rpx;" @click="butBleFn">
				<u-button type="primary" shape="circle" :color="butcolor" :text="rightText"></u-button>
			</view>

			<!-- 		<u-navbar :autoBack="true" placeholder bgColor="#d6e0e6" :safeAreaInsetTop="true" title="个人中心"
				:fixed="false" :rightText="rightText" >
			</u-navbar> -->
		</view>
		<view class="home">
			<view class="input_item">
				<view class="text">
					设备串口地址：
				</view>
				<view class="input">
					{{dataObj.address}}
				</view>
			</view>
			<view class="input_item">
				<view class="text" style="padding: 0;">
					<u-button type="warning" shape="circle" text="修改串口地址" @click="newaddressFn"></u-button>
				</view>
				<view class="input">
					<u--input placeholder="输入 0 - 254 整数" clearable type="digit" border="bottom"
						v-model="newaddress"></u--input>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					水文遥测站编码：
				</view>
				<view class="input">
					<u--input placeholder="长度为10的数字整数" type="digit" clearable border="bottom"
						v-model="dataObj.code"></u--input>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					水文中心站地址：
				</view>
				<view class="input">
					<u--input placeholder=" 0 - 254 整数" clearable type="digit" border="bottom"
						v-model="dataObj.center"></u--input>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					经度：
				</view>
				<view class="input">
					<u--input placeholder="精确到小数点后6位" clearable type="digit" border="bottom"
						v-model="dataObj.lon"></u--input>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					纬度：
				</view>
				<view class="input">
					<u--input placeholder="精确到小数点后6位" clearable type="digit" border="bottom"
						v-model="dataObj.lat"></u--input>
				</view>
			</view>
			<u-button style="margin-bottom: 10rpx;" type="warning" shape="circle" size="mini" text="获取手机经纬度"
				@click="latlon"></u-button>
			<view class="input_item">
				<view class="text">
					密码：
				</view>
				<view class="input">
					<u--input placeholder="长度为4,范围0-6000" clearable type="digit" border="bottom"
						v-model="dataObj.password"></u--input>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					数据类型：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.types" :localdata="types" @change="typesChange"></uni-data-select>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					雨量分辨力：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.rainfall" :localdata="rainfall"
						@change="rainfallChange"></uni-data-select>
				</view>
			</view>

			<view class="input_item">
				<view class="text">
					昨日雨量生成时间：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.reporgenerationTime" :localdata="rainTime"
						@change="yesterdaysRainfallChange"></uni-data-select>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					变频雨量上报周期：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.reportingCycle" :localdata="cycleTime"
						@change="reportingChange"></uni-data-select>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					每日定时上报次数：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.numberOfReports" :localdata="numbersTime"
						@change="numberOfsChange"></uni-data-select>
				</view>
			</view>
			<view class="input_item">
				<view class="text">
					电池类型：
				</view>
				<view class="input">
					<uni-data-select v-model="dataObj.batteryType" :localdata="batteryList"
						@change="batteryTypeChange"></uni-data-select>
				</view>
			</view>
<!-- 			<view class="input_item">
				<view class="text">
					蓝牙等待时间：
				</view>
				<view class="input">
					<u--input placeholder="30-250" clearable type="digit" border="bottom" disabled
						v-model="dataObj.bluTime"></u--input>
				</view>
			</view> -->
			<!-- 旧修改 -->
			<u-button style="margin: 40rpx 0;" type="primary" shape="circle" text="获取参数" @click="query"></u-button>
			<u-button style="margin: 40rpx 0;" type="success" shape="circle" text="修改设备参数" @click="modify"></u-button>
			<u-toast ref="uToast"></u-toast>
		</view>
	</view>

</template>

<script>
	// import circleProgress from '../../../../uni_modules/uview-ui/libs/config/props/circleProgress';
	export default {
		data() {
			return {
				butcolor: '#be3131',
				rightText: '未连接设备',
				newaddress: null,
				dataObj: {
					address: null,
					code: '',
					lon: null,
					lat: null,
					password: null,
					types: null,
					rainfall: null,
					center: null, //中心站地址
					reporgenerationTime: null, //昨日雨量生成时间
					reportingCycle: null, //上报周期
					numberOfReports: null, //每日定时上报次数
					batteryType: null, //电池类型
					bluTime: '250' //蓝牙等待时间
				},
				// dataObj: {
				// 	address: 12,
				// 	code: '12345',
				// 	lon: 144.567888,
				// 	lat: 38.123456,
				// 	password: 5479,
				// 	types: 1,
				// 	rainfall: 2,
				// 	center: 3
				// },
				types: [{
						value: 1,
						text: "JSON协议"
					},
					{
						value: 6,
						text: "651协议"
					}
				],
				rainfall: [{
						value: 1,
						text: "0.1毫米"
					},
					{
						value: 2,
						text: "0.2毫米"
					},
					{
						value: 3,
						text: "0.3毫米"
					},
					{
						value: 5,
						text: "0.5毫米"
					},
					{
						value: 10,
						text: "1毫米"
					}
				],
				rainTime: [{
						value: 0,
						text: "0时"
					},
					{
						value: 8,
						text: "8时"
					}
				],
				cycleTime: [{
						value: 1,
						text: "1"
					},
					{
						value: 2,
						text: "2"
					},
					{
						value: 3,
						text: "3"
					},
					{
						value: 4,
						text: "4"
					},
					{
						value: 5,
						text: "5"
					},
					{
						value: 6,
						text: "6"
					},
					{
						value: 7,
						text: "7"
					},
					{
						value: 8,
						text: "8"
					},
					{
						value: 9,
						text: "9"
					}
				],
				numbersTime: [{
						value: 1,
						text: "1次"
					},
					{
						value: 4,
						text: "4次"
					},
					{
						value: 24,
						text: "24次"
					}
				],
				batteryList: [{
						value: 1,
						text: "锂三串9.0V-12.6V"
					},
					{
						value: 2,
						text: "锂四串12.0V-16.8V"
					},
					{
						value: 3,
						text: "磷酸铁锂10.6-14.6V"
					},
					{
						value: 4,
						text: "铅酸11.0V-13.8V"
					},
					{
						value: 5,
						text: "锂二串6.0V-8.4V"
					}
				],
				value: '',
				deviceId: '', //蓝牙
				serviceId: '', //蓝牙
				characteristicId: '', //蓝牙
				fff: '', //蓝牙
				vuexlist: {},
				toaIf: true,
			}
		},
		onUnload() {
			console.log('卸载');
		},
		onShow() {
			// uni.showToast({
			// 	title: '',
			// 	icon: 'loading',
			// 	mask: true,
			// 	duration: 1500
			// });
			// 断开设备
			uni.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				if (res.connected !== true) {
					this.butcolor = '#be3131'
					this.rightText = '未连接设备'
					uni.$u.vuex('vuex_devicename', '')
					uni.$u.vuex('vuex_deviceId', '')
					uni.navigateBack({
						delta: 2
					});
				}
			})
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			setTimeout(() => {
				uni.hideLoading();
			}, 3000);

			this.deviceId = this.vuex_deviceId
			this.getBLEDeviceServices()
		},
		onLoad(option) {

		},
		methods: {
			backFn() {
				uni.navigateBack({
					delta: 1
				});
			},
			butBleFn() {
				// if (this.rightText == '设备已连接') {
				// 	this.duankai()
				// } else {
				// 	uni.navigateTo({
				// 		url: '/pages/index/BLE'
				// 	});
				// }
			},
			duankai() {
				uni.closeBLEConnection({
					deviceId: this.vuex_deviceId,
					success: (res) => {
						this.lanname = ''
						uni.$u.vuex('vuex_devicename', '')
						uni.$u.vuex('vuex_deviceId', '')
						this.butcolor = '#be3131'
						this.rightText = '未连接设备'
					}
				})

			},
			//修改新地址
			newaddressFn() {
				let msg = ['', '06', 'ff', '02', '00', '', '', '']
				let addre = this.decimalToHex(this.dataObj.address * 1)
				let newaddre = this.decimalToHex(this.newaddress * 1)
				msg[0] = addre
				msg[5] = newaddre
				let arrstr = msg[0] + msg[1] + msg[2] + msg[3] + msg[4] + msg[5]
				let crcstr = this.crc16(arrstr)
				let montage = arrstr + crcstr[1] + crcstr[0]
				let arr = this.chunkStringByTwo(montage).map((i) => {
					return '0x' + i
				})
				console.log('msg---', msg);
				console.log('arrstr---', arrstr);
				console.log('crcstr---', crcstr);
				console.log('montage---', montage);
				console.log('arr---', arr);
				this.conbuffer(arr)
			},
			// 手机获取经纬度
			latlon() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						console.log('当前位置的经度：' + res.longitude.toFixed(6));
						console.log('当前位置的纬度：' + res.latitude.toFixed(6));
						this.dataObj.lon = res.longitude.toFixed(6) + ''
						this.dataObj.lat = res.latitude.toFixed(6) + ''
					}
				});

			},
			// 数据类型
			typesChange(e) {
				this.dataObj.types = e
				console.log('e', e);
			},
			// 雨量分辨力
			rainfallChange(e) {
				this.dataObj.rainfall = e
				console.log('e', e);
			},
			// 昨日雨量生成时刻
			yesterdaysRainfallChange(e) {
				this.reporgenerationTime = e
			},
			// 变频雨量上报周期
			reportingChange(e) {
				this.reportingCycle = e
			},
			// 每日定时上报次数
			numberOfsChange(e) {
				this.numberOfReports = e
			},
			// 电池类型
			batteryTypeChange(e) {
				this.batteryType = e
			},

			// 查询地址
			query() {
				// let msg = ['0x0c', '0x03', '0xf0', '0x00', '0x00', '0x0c', '0x77', '0xD2']
				let msg = ['0x00', '0x03', '0xff', '0x02', '0x00', '0x01', '0x14', '0x0f']
				this.conbuffer(msg)
			},
			// 返回查询地址
			queryReturn(num) {
				this.dataObj.address = this.hexToDecimal(num)
				this.queryData(num)
			},
			// 查询数据
			queryData(num) {
				let msg = ['', '03', 'f0', '00', '00', '0c']
				msg[0] = num
				let msgcrc = msg.reduce((accumulator, currentValue) => {
					return accumulator + currentValue;
				}, '');
				let crc = this.crc16(msgcrc)
				let msgBLE = msgcrc + crc[1] + crc[0]
				let arr = []
				arr = this.chunkStringByTwo(msgBLE).map((i) => {
					return '0x' + i
				})
				this.conbuffer(arr)
			},
			// 查询数据返回内容
			queryDataReturn(data) {
				this.dataObj.code = data.slice(0, 10) + '' //编码
				this.dataObj.lon = this.hexToDecimal(data.slice(10, 18)) / 1000000 //经度
				this.dataObj.lat = this.hexToDecimal(data.slice(18, 26)) / 1000000 //纬度
				this.dataObj.password = this.hexToDecimal(data.slice(26, 30)) //密码
				this.dataObj.types = this.hexToDecimal(data.slice(30, 32)) //协议
				this.dataObj.rainfall = this.hexToDecimal(data.slice(32, 34)) //分辨力
				this.dataObj.center = this.hexToDecimal(data.slice(34, 36)) //中心站
				this.dataObj.reporgenerationTime = this.hexToDecimal(data.slice(36, 38)) //昨日雨量生成时
				this.dataObj.reportingCycle = this.hexToDecimal(data.slice(38, 40)) //变频雨量上报周期
				this.dataObj.numberOfReports = this.hexToDecimal(data.slice(40, 42)) //每日上报次数
				this.dataObj.batteryType = this.hexToDecimal(data.slice(42, 44)) //电池类型
				this.dataObj.bluTime = this.hexToDecimal(data.slice(44, 46)) //蓝牙等待时间

				console.log('this.dataObj', this.dataObj);
			},
			modify() {
				// 编码
				if (this.dataObj.code.length != 10 && uni.$u.test.digits(this.dataObj.code)) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "中心站地址",
						position: 'top'
					})
					return
				}
				//判断
				console.log('OBJ', this.dataObj);
				// 地址
				if (this.dataObj.address == '' || this.dataObj.address <= 0 || this.dataObj.address > 254) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "设备地址格式不正确",
						position: 'top'
					})
					return
				}

				// 经度
				if ((this.dataObj.lon + '').length != 10) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "经度格式不正确",
						position: 'top'
					})
					return
				}
				// 纬度
				if ((this.dataObj.lat + '').length != 9) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "纬度格式不正确",
						position: 'top'
					})
					return
				}
				// 密码
				if ((this.dataObj.password + '').length != 4) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "密码格式不正确",
						position: 'top'
					})
					return
				}
				// 类型
				if (this.dataObj.types == null || this.dataObj.types == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "数据类型未选择",
						position: 'top'
					})
					return
				}
				// 分辨力
				if (this.dataObj.rainfall == null || this.dataObj.rainfall == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "分辨力未选择",
						position: 'top'
					})
					return
				}
				// 中心站
				if (this.dataObj.center == '' || this.dataObj.center <= 0 || this.dataObj.center > 254) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "中心站格式不正确",
						position: 'top'
					})
					return
				}
				// 生成时间
				if (this.dataObj.reporgenerationTime == null) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "生成时间未选择",
						position: 'top'
					})
					return
				}
				// 上报周期
				if (this.dataObj.reportingCycle == null || this.dataObj.reportingCycle == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "上报周期未选择",
						position: 'top'
					})
					return
				}
				// 上报次数
				if (this.dataObj.numberOfReports == null || this.dataObj.numberOfReports == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "上报次数未选择",
						position: 'top'
					})
					return
				}
				// 电池类型
				if (this.dataObj.batteryType == null || this.dataObj.batteryType == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "电池类型未选择",
						position: 'top'
					})
					return
				}
				// 蓝牙等待时间
				if (this.dataObj.bluTime == null || this.dataObj.bluTime == '') {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "蓝牙等待时间未选择",
						position: 'top'
					})
					return
				}
				let obj = this.dataObj
				let address = this.decimalToHex(obj.address * 1) //地址
				let code = obj.code //水文遥测站编码
				let lon = this.decimalToHex(obj.lon * 1000000) //经度
				let lat = this.decimalToHex(obj.lat * 1000000) //纬度
				let password = this.decimalToHex(obj.password * 1) //密码
				let types = this.decimalToHex(obj.types * 1) //类型
				let rainfall = this.decimalToHex(obj.rainfall * 1) //分辨力
				let center = this.decimalToHex(obj.center * 1) //中心站
				let yesterdayRa = this.decimalToHex(obj.reporgenerationTime * 1) //昨日雨量生成时间
				let cycleday = this.decimalToHex(obj.reportingCycle * 1) //变频雨量上报周期
				let numReport = this.decimalToHex(obj.numberOfReports * 1) //每日上报次数
				let typebattery = this.decimalToHex(obj.batteryType * 1) //电池类型
				let bluTime = this.decimalToHex(obj.bluTime * 1) //蓝牙等待时间

				let str = address + '10' + 'f000000c' + '18' + code + lon + lat + password + types + rainfall + center +
					yesterdayRa + cycleday + numReport + typebattery + bluTime + '00'
				console.log('拼接', str, str.length);
				let crc = this.crc16(str)
				console.log('修改', address, code, lon, lat, password, types, rainfall, center, yesterdayRa, cycleday,
					numReport, typebattery, bluTime);


				let msgBLE = str + crc[1] + crc[0]
				console.log(msgBLE, msgBLE.length);
				let arr = []
				arr = this.chunkStringByTwo(msgBLE).map((i) => {
					return '0x' + i
				})
				console.log('arr', arr, arr.length);
				this.conbuffer(arr)

			},
			//监听消息变化
			listenValueChange() {
				setTimeout(() => {
					uni.onBLECharacteristicValueChange(res => {
						let resHex = this.ab2hex(res.value)
						console.log('监听初始化数据', resHex, resHex.length);
						// 广播获取地址
						if (resHex.length == 14) {
							// 隐藏toa
							this.toaIf = false
							let num = resHex.slice(8, 10)
							this.queryReturn(num)
						}
						//获取设备参数
						if (resHex.length == 58) {

							let num = resHex.slice(6)
							this.queryDataReturn(num)
						}
						//写入设备
						if (resHex.length == 16) {
							uni.showToast({
								title: '修改成功',
								icon: 'loading',
								mask: true,
								duration: 1500
							});
							// this.$refs.uToast.show({
							// 	type: 'success',
							// 	icon: false,
							// 	message: "修改成功",
							// 	position: 'top'
							// })
							console.log('写入');
						}
					})
				}, 300)
			},
			// 分割字符串
			chunkStringByTwo(str) {
				const result = [];
				for (let i = 0; i < str.length; i += 2) {
					result.push(str.slice(i, i + 2));
				}
				return result;
			},
			// CRC16校验
			crc16(dataHexString) {
				const dataBytes = [];
				for (let i = 0; i < dataHexString.length; i += 2) {
					dataBytes.push(parseInt(dataHexString.substr(i, 2), 16));
				}

				let crc = 0xFFFF;
				const polynomial = 0xA001; // This is the polynomial x^16 + x^15 + x^2 + 1

				for (const byte of dataBytes) {
					crc ^= byte;
					for (let i = 0; i < 8; i++) {
						if (crc & 0x0001) {
							crc = ((crc >> 1) ^ polynomial) & 0xFFFF;
						} else {
							crc >>= 1;
						}
					}
				}
				let crcstr = crc.toString(16).toUpperCase();
				if (crcstr.length % 2 == 0) {
					let result = crcstr.match(/.{1,2}/g)
					return result;
				} else {
					let str = '0' + crcstr
					let result = str.match(/.{1,2}/g)
					return result;
				}
			},
			// crc16(data) {
			// 	let crcValue = 0xFFFF;
			// 	for (let i = 0; i < data.length; i++) {
			// 		crcValue ^= data[i] & 0xFFFF
			// 		for (let j = 0; j < 8; j++) {
			// 			if (crcValue & 0x0001) {
			// 				crcValue >>= 1
			// 				crcValue ^= 0xA001
			// 			} else {
			// 				crcValue >>= 1
			// 			}
			// 		}
			// 	}

			// 	crcValue = crcValue.toString(16)
			// 	let crcArr = new Array(2)
			// 	crcArr[0] = crcValue.substring(2, 4)
			// 	crcArr[1] = crcValue.substring(0, 2)
			// 	return crcArr
			// },
			// 16进制转10进制
			hexToDecimal(hex) {
				return parseInt(hex, 16);
			},
			// 10进制转16进制
			decimalToHex(decimal) {
				let hex = decimal.toString(16).toUpperCase();
				if (hex.length % 2 !== 0) {
					return '0' + hex
				} else {
					return hex
				}
				// return decimal.toString(16).toUpperCase();
			},
			// 16进制转字符串
			hexToString(hex) {
				let str = '';
				for (let i = 0; i < hex.length; i += 2) {
					let charCode = parseInt(hex.substr(i, 2), 16);
					str += String.fromCharCode(charCode);
				}
				return str;
			},
			//字符串转16进制
			stringToHex(str) {
				return str.split('').map(function(char) {
					return char.charCodeAt(0).toString(16).padStart(2, '0');
				}).join('');
			},
			/**
			 * 数字字符串转BCD码
			 * @param {string} digitString - 数字字符串
			 * @returns {number[]} BCD字节数组
			 */
			digitStringToBCDHex(digits) {
				if (!/^\d+$/.test(digits)) {
					throw new Error('输入必须为数字字符串');
				}

				const bcdBytes = [];

				for (let i = 0; i < digits.length; i += 2) {
					const highDigit = parseInt(digits[i]);

					if (i + 1 < digits.length) {
						const lowDigit = parseInt(digits[i + 1]);
						const bcdByte = (highDigit << 4) | lowDigit;
						bcdBytes.push('0x' + bcdByte.toString(16).toUpperCase().padStart(2, '0'));
					} else {
						const bcdByte = highDigit << 4;
						bcdBytes.push('0x' + bcdByte.toString(16).toUpperCase().padStart(2, '0'));
					}
				}

				return bcdBytes;
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			// 输入蓝牙数据
			conbuffer(data) {
				let msg = data
				// 向蓝牙设备发送一个0x00的16进制数据
				const buffer = new ArrayBuffer(msg.length)
				const dataView = new DataView(buffer)
				// dataView.setUint8(0, 0)
				for (var i = 0; i < msg.length; i++) {
					// dataView.setUint8(i, msg.charAt(i).charCodeAt())
					dataView.setUint8(i, msg[i]);
				}
				this.sendMsgToKey(buffer)
			},
			/* 向设备发送消息(分包发送，单包20字节，递归发送)
			 */
			sendMsgToKey(buffer) {
				// console.log('buffer', buffer);
				var that = this //vue中的this
				const packageSize = 20 //分包大小
				if (buffer.byteLength <= 20) { //如果小于20直接发送，不再继续调用
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buffer,
						writeType: 'write',
						success: (res) => {
							//此时设备已接收到你写入的数据
							console.log('写入111');

						},
						fail: (err) => {
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				} else { //如果大于20发送完成后继续递归调用
					var newData = buffer.slice(20)
					var writeBuffer = buffer.slice(0, 20)
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: writeBuffer,
						writeType: 'write',
						success: function(res) {
							console.log('写入222');
							//写入后继续递归调用发送剩下的数据
							setTimeout(() => {
								that.sendMsgToKey(newData)
							}, 100)
						},
						fail: (err) => {
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				}
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.vuex_deviceId,
						success: (res) => {
							console.log('获取蓝牙所有服务', res);
							//E95D93AF-251D-470A-A062-FA1922DFA9A8
							//6E400001-B5A3-F393-E0A9-E50E24DCCA9E
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log('获取蓝牙特征值');
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {

							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {

								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("0000FFE1") != -1) {

									this.characteristicId = item.uuid
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								if (item.uuid.indexOf("0000FFF1") != -1) {

									this.characteristicId = item.uuid


									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				console.log('启用 notify 功能');
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,

					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('蓝牙名字', res);
						// vuex
						// uni.$u.vuex('vuex_devicename', this.vuexlist.name)
						uni.hideLoading()
						this.listenValueChange()
						// uni.showToast({
						// 	title: '服务已开启',
						// 	icon: 'success',
						// 	mask: true,
						// 	duration: 1000
						// });
						// uni.hideToast();
						this.butcolor = '#00aa7f'
						this.rightText = '设备已连接'
						setTimeout(() => {
							this.query()
						}, 1000)
						// uni.showToast({
						// 	title: '信息获取中...',
						// 	icon: 'loading',
						// 	mask: true,
						// 	duration: 10000
						// });
					},
					fail: (res) => {
						uni.hideLoading()
						uni.showToast({
							title: '获取服务失败',
							icon: 'fail',
							mask: true,
							duration: 1000
						});

					}
				})

			},
		}
	}
</script>
<style scoped lang="scss">
	.box {
		.upage__item {
			margin-top: 80rpx;
			padding: 0 30rpx 10rpx 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.home {
			padding: 30rpx;
			border-radius: 30rpx;
			// border: 1rpx solid #000000;
			// background-color: #ffffff;

			.input_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				// margin: 15rpx 0;
				padding: 5rpx 10rpx;
				margin-bottom: 15rpx;
				border-radius: 20rpx;
				border: 5rpx solid #fff;
				background-color: #ffffff;

				.text {
					color: #000000;
					text-align: justify;
					text-align-last: justify;
					padding: 15rpx;
					border-radius: 10rpx;
					// width: 350rpx;
					// background-color: #c13b2f;
				}

				.input {
					width: 320rpx;
					// background-color: #32c1ac;
				}
			}
		}
	}
</style>
<style>
	page {
		background-color: #f2f1f6;
	}
</style>